package com.clock.web.controller.shop;


import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;

import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.clock.common.config.AliPayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
//import com.alipay.api.response.AlipayTradePrecreateResponse;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.factory.Factory.Payment;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;

import com.clock.common.config.F2FPayConfig;
import com.clock.shop.domain.ShopOrder;
import com.clock.shop.service.IShopOrderService;
import org.springframework.security.config.web.servlet.oauth2.resourceserver.OAuth2ResourceServerSecurityMarker;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController
{

    //支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    private static final String FORMAT = "JSON";

    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig alipayConfig;

    @Resource
    private IShopOrderService iShopOrderService;


    /**
     * 客户端支付
     */
    @GetMapping("/pay")
    public void pay(String orderId, HttpServletResponse httpServletResponse) throws Exception {
        //查询订单信息
        ShopOrder shopOrder = iShopOrderService.selectShopOrderByOrderId(Long.valueOf(orderId));
        if(shopOrder == null) {
            return;
        }

        //1.创建Client,通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SIGN_TYPE);

        //2.创建Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", shopOrder.getOrderId()); //我们自己生成的订单编号
        bizContent.put("total_amount", shopOrder.getPaymoney());//订单的总金额
        bizContent.put("subject", shopOrder.getServiceName());//支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY ");//固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:8080//shop/Cashier");//支付完成后自动跳转到本地页面的路径
        /*
        支付宝官方返回的页面
        执行请求，拿到相应的结果，返回给路由器
         */
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();//调用SDK生成表单
        }catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpServletResponse.setContentType("text/html;charset=" + CHARSET);
        httpServletResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
        }

    /**
     * 收银时-支付宝面对面付款
     */
    @GetMapping("/face2FacePay")
    public void face2FacePay(String orderId, HttpServletResponse httpServletResponse) throws Exception{
        F2FPayConfig f2FPayConfig = new F2FPayConfig();
        //查询订单信息
        ShopOrder shopOrder = iShopOrderService.selectShopOrderByOrderId(Long.valueOf(orderId));
        if(shopOrder == null) {
            return;
        }
        /** 初始化 **/
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(),
        alipayConfig.getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SIGN_TYPE);

        /** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称：alipay.trade.precreate（统一收单线下交易预创建（扫码支付）） **/
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        try {
            // 调用支付宝接口
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(shopOrder.getServiceName(), String.valueOf(shopOrder.getOrderId()), String.valueOf(shopOrder.getPaymoney()));
            // 解析结果
            String httpBody = response.getHttpBody();
            JSONObject jsonObject = JSONObject.parseObject(httpBody);
            String qrUrl = jsonObject.getJSONObject("alipay_trade_response").get("qr_code").toString();
            // 生成二维码
            BufferedImage qrImage = QrCodeUtil.generate(qrUrl, 300, 300);
            // 将BufferedImage转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(qrImage, "png", baos);
            byte[] imageData = baos.toByteArray();
            // 设置HTTP响应内容类型和头部信息
            httpServletResponse.setContentType("image/png");
            httpServletResponse.setHeader("Content-Disposition", "inline; filename=\"qrcode.png\"");
            // 将图片数据写入响应输出流
            OutputStream os = httpServletResponse.getOutputStream();
            os.write(imageData);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            // 记录异常信息或返回错误响应
        }
//
//        //调用支付宝接口
//        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(shopOrder.getServiceName(), String.valueOf(shopOrder.getOrderId()),
//                String.valueOf(shopOrder.getPaymoney()));
//        //解析结果
//        String httpBody = response.getHttpBody();
//        JSONObject jsonObject = JSONObject.parseObject(httpBody);
//        String qrUrl = jsonObject.getJSONObject("alipay_trade_response").get("qr_code").toString();
//
//        //生成二维码
//        BufferedImage qrImage = QrCodeUtil.generate(qrUrl, 300, 300);
//
//        // 将BufferedImage转换为字节数组（这里使用Java的ImageIO库）
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        ImageIO.write(qrImage, "png", baos); // 假设你的二维码是PNG格式
//        byte[] imageData = baos.toByteArray();
//
//        // 设置HTTP响应内容类型和头部信息
//        httpServletResponse.setContentType("image/png"); // 根据实际情况设置内容类型，如果是JPG则设置为"image/jpeg"
//        httpServletResponse.setHeader("Content-Disposition", "inline; filename=\"qrcode.png\""); // 附加文件头提供下载时的文件名
//
//        // 将图片数据写入响应输出流
//        OutputStream os = httpServletResponse.getOutputStream();
//        os.write(imageData);
//        os.flush(); // 刷新输出流，确保数据被发送出去
//        os.close(); // 关闭输出流

        }


    @PostMapping("/notify")
    public String payNotify(HttpServletRequest httpServletRequest) throws Exception {
        if (httpServletRequest.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付异步回调=========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, httpServletRequest.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), "UTF-8");
            //支付验签
            if (checkSignature) {
                //验证通过
                System.out.println("交易名称：" + params.get("subject"));
                System.out.println("交易状态：" + params.get("trade_status"));
                System.out.println("支付宝交易凭证号：" + params.get("trade_no"));
                System.out.println("商户订单号：" + params.get("out_trade_no"));
                System.out.println("交易金额：" + params.get("total_amount"));
                System.out.println("卖家在支付宝唯一id：" + params.get("buyer_id"));
                System.out.println("买家付款时间" + params.get("gmt_create_time"));
                System.out.println("买家付款金额：" + params.get("buyer_pay_amount"));

                String tradeNo = params.get("out_trade_no");//订单编号
                String gmtPayment = params.get("gmt_payment");//支付时间
                String alipayTradeNo = params.get("trade_no");//支付宝交易编号

                //更改订单状态为已支付，设置支付信息
                ShopOrder shopOrder = iShopOrderService.selectShopOrderByOrderId(Long.valueOf(tradeNo));
                shopOrder.setPayStatus(String.valueOf(1));

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDateTime = LocalDateTime.parse(gmtPayment, formatter);
                Date payTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                shopOrder.setPayTime(payTime);

//                shopOrder.setPayNo(alipayTradeNo);
//                shopOrder.updateShopOrder(shopOrder);

            }

        return "success";
        }
        return "error";
    }
}
